package com.century.sjt.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.century.sjt.R;
import com.century.sjt.adapter.BankCardAdapter;
import com.century.sjt.entity.BankCard;
import com.century.sjt.util.Constant;
import com.century.sjt.util.TipUtil;
import com.century.sjt.widget.TitleBar.SjtTitleBar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @author:周玲波
 * @Description:银行卡
 * @date : 2016/8/17 16:17
 */
public class BankCardActivity extends BaseActivity {
    @BindView(R.id.bank_card_title)
    SjtTitleBar mSjtTitleBar;
    private BankCardAdapter adapter;
    private ListView listView;
    private List<BankCard> mDatalist;
    private Handler mHandler;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sjt_bank_card_activity);
        ButterKnife.bind(this);
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        adapter.notifyDataSetChanged();
                        break;
                }
            }
        };

        initView();

        initData();

        initEvent();

    }

    @Override
    protected void initView() {
        mSjtTitleBar.setTitle(getResources().getString(R.string.tab_bankcard));
        mSjtTitleBar.setLeftIconResource(getResources().getString(R.string.icon_return));
        mSjtTitleBar.setRightIconResourc(getResources().getString(R.string.icon_plus));
        mSjtTitleBar.setRightLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(BankCardActivity.this, AddBankActivity.class);
            }
        });
        mSjtTitleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        listView = (ListView) findViewById(R.id.lv_listview);
        mDatalist = new ArrayList<>();
    }

    @Override
    protected void initEvent() {

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent();
                //待做
                intent.setClass(BankCardActivity.this, BankDataAcitvity.class);
                Bundle bundle = new Bundle();
                bundle.putString("phone", mDatalist.get(position).getPhone());
                bundle.putString("bankCardNo", mDatalist.get(position).getBankCardNo());
                bundle.putString("bankCode", mDatalist.get(position).getBankCode());
                bundle.putString("bankName", mDatalist.get(position).getCardName());
                bundle.putString("bankType", mDatalist.get(position).getCardTypeName());
                bundle.putString("status", mDatalist.get(position).getStatus());
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
    }

    @Override
    protected void initData() {
        // 设置适配器
        adapter = new BankCardAdapter(BankCardActivity.this, mDatalist, mQueue);
        listView.setAdapter(adapter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        getBindBankCard();
    }

    /**
     * 获取绑定的银行卡
     */
    private void getBindBankCard() {
        mDatalist.clear();
        //显示Progress Dialog
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.error_please_waitting), BankCardActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.GetBindBankCardHost, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    TipUtil.log("获取绑定的银行卡接口成功返回", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//成功
//                        TipUtil.showToast(message, BankcardActivity.this, 1);
//                        判断是否有获取到银行卡，从而改变本地的是否绑定银行卡变量
                        JSONObject data = res.getJSONObject("data");
//                        SharedPreferences.Editor editor = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE).edit();
//                        if(data.length()==0){
//                            editor.putString("isBlind", "0");
//                        }else {
//                            editor.putString("isBlind", "1");
//                        }
//                        editor.commit();
//                      判断是否有获取到银行卡，从而改变本地的是否绑定银行卡变量（end）
                        JSONArray cardList = data.getJSONArray("cardList");
                        for (int i = 0; i < cardList.length(); i++) {
                            JSONObject item = (JSONObject) cardList.get(i);
                            BankCard bankCard = new BankCard();
                            bankCard.setPhone(item.getString("phone"));
                            bankCard.setCardName(item.getString("bankName"));
                            bankCard.setStatus(item.getString("status"));
                            bankCard.setBankCardNo(item.getString("bankCardNo"));
                            bankCard.setBankCode(item.getString("bankCode"));
                            bankCard.setCardTypeName(item.getString("cardTypeName"));
                            bankCard.setCardType(item.getString("cardType"));

                            mDatalist.add(bankCard);
                        }
                        Message msg = new Message();
                        msg.what = 1;
                        mHandler.sendMessage(msg);

                    } else {//失败
                        TipUtil.showToast(message, BankCardActivity.this, 1);
                    }
                } catch (JSONException ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service), BankCardActivity.this, 1);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), BankCardActivity.this, 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
                return map;

            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
//                Log.e("cookie", cookieValue);
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);

    }


}
